package com.sec.android.app.myfiles.facade;

import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;

import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.util.JUnitHandler;

import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;

public abstract class AbsSimpleThreadCmd extends SimpleCommand {
    private static HandlerThread sThread;
    private static CmdHandler sCmdHandler;
    private static final String THREAD_NAME = "SimpleThreadCmd";

    protected abstract void executeThread(INotification notification);

    private static class ReqCmdInfo {
        ReqCmdInfo(AbsSimpleThreadCmd caller, INotification notification) {
            mCaller = caller;
            mNotification = notification;
        }

        public AbsSimpleThreadCmd mCaller;
        public INotification mNotification;
    }

    @Override
    public final void execute(INotification notification) {
        if (sThread == null) {
            createThread();
        }

        if (sCmdHandler == null) {
            createHandler();
        }

        if (sCmdHandler != null) {
            sCmdHandler.sendMessage(sCmdHandler.obtainMessage(0, new ReqCmdInfo(this, notification)));
        }
    }

    private synchronized void createThread() {
        if (sThread == null) {
            sThread = new HandlerThread(THREAD_NAME, Process.THREAD_PRIORITY_BACKGROUND);
            sThread.start();
            Log.d(this, "createThread : sThread is created");
        } else {
            Log.d(this, "createThread : sThread was null but created alread");
        }
    }

    private synchronized void createHandler() {
        if (sCmdHandler == null) {
            Looper looper = sThread.getLooper();
            if (looper != null) {
                sCmdHandler = new CmdHandler(looper);
                Log.d(this, "createHandler : sCmdHandler is created");
            }
        } else {
            Log.d(this, "createHandler : sCmdHandler was null but created alread");
        }
    }

    private static final class CmdHandler extends JUnitHandler<ReqCmdInfo> {
        public CmdHandler(Looper looper) {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg) {
            if (msg != null) {
                ReqCmdInfo req = getMsgValue(msg.obj);
                req.mCaller.executeThread(req.mNotification);
            }
        }
    }

}
